package com.ttpai.boot.lbs.service.ok;

import com.ttpai.boot.lbs.dao.BossInvitationDAO;
import com.ttpai.boot.lbs.model.BossInvitationVO;
import com.ttpai.boot.lbs.service.BaiduLbsService;
import com.ttpai.boot.lbs.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by kail on 2017/3/11.
 */
@Service
public class RealInvitationService {

    private static final Logger logger = LoggerFactory.getLogger(RealInvitationService.class);

    @Autowired
    private BossInvitationDAO bossInvitationDAO;

    @Autowired
    private BaiduLbsService baiduLbsService;

    /**
     * 抓取原始数据经纬度
     */
    public void fetchLangLat() {
        List<BossInvitationVO> select = selectByDateAndCity("上海", DateUtil.format("2017-02-26"));

        for (BossInvitationVO vo : select) {
            String cityName = vo.getCityName();
            String areaName = StringUtils.isBlank(vo.getAreaName()) ? "" : vo.getAreaName();
            String address = vo.getAddress();

            String lngLat = baiduLbsService.fetchLngLat(cityName, areaName + address);
            logger.info(lngLat);

            String[] langAndLat = lngLat.split(",");

            BossInvitationVO updateVO = new BossInvitationVO();
            updateVO.setAuctionId(vo.getAuctionId());
            updateVO.setLng(Double.valueOf(langAndLat[0]));
            updateVO.setLat(Double.valueOf(langAndLat[1]));
            bossInvitationDAO.update(updateVO);
        }
    }

    /**
     * 获取某个城市某一天的原始数据
     */
    public List<BossInvitationVO> selectByDateAndCity(String cityName, Date checkDate) {
        BossInvitationVO selectVO = new BossInvitationVO();
        selectVO.setCityName(cityName);
        selectVO.setCheckTime(checkDate);
        return bossInvitationDAO.select(selectVO);
    }

    /**
     * 获取某个城市某一天的原始数据
     */


    public Map<Integer, BossInvitationVO> selectByDateAndCityMap(String cityName, Date checkDate) {
        List<BossInvitationVO> invitationVOS = this.selectByDateAndCity(cityName, checkDate);
        Map<Integer, BossInvitationVO> map = new HashMap<>();
        for (BossInvitationVO invitationVO : invitationVOS) {
            map.put(invitationVO.getAuctionId(), invitationVO);
        }
        return map;
    }

    public Map<Integer, BossInvitationVO> cache = null;

    public BossInvitationVO selectCacheByAuction(Integer auctionId) {
        if (null == cache) {
            List<BossInvitationVO> bossInvitationVOS = bossInvitationDAO.select(new BossInvitationVO());
            cache = new HashMap<>();
            for (BossInvitationVO bossInvitationVO : bossInvitationVOS) {
                cache.put(bossInvitationVO.getAuctionId(), bossInvitationVO);
            }
        }
        return cache.get(auctionId);
    }


}
